# File:     regression_daughters.R
# Purpose:  This script estimates the degree to which the hostility toward yellen is moderated by daughters
# Input:    /Data/finalData.RData
# Output:   /Paper/Figures/firstDaughter_mfx.pdf
#           /Paper/Figures/anyDaughters_mfx.pdf
#           /Paper/Figures/nDaughters_mfx.pdf
#           /Paper/Figures/propDaughters_mfx.pdf
# Author:   JB


rm(list = ls())
require(lme4)
require(lfe)
require(tidyverse)
require(ggridges)


# Functions
source('./helper_functions.R')

load('../Data/finalData.RData')


# What about isolating evidence of kids / feminism?
colnames(speaker_level)
toAnalDyadKids <- speaker_level %>% 
  mutate(anyDaughters = ifelse(nDaughters == 0,0,1),
         propDaughters = nDaughters / nKids,
         noKids = ifelse(nKids == 0,1,0)) %>%
  mutate(propDaughters = ifelse(is.na(propDaughters),0,propDaughters)) %>%
  mutate(respondingTo = relevel(factor(respondingTo),ref = 'FEDBERNANKE'))

modList <- list()
for(mod in c('nDaughters','firstDaughter','anyDaughters','propDaughters')) {
  for(chamb in c('House','Senate')) {
    for(period in c('Bernanke->Yellen','Yellen->Powell','Full')) {
      if(period == 'Bernanke->Yellen') {
        start <- '2006-01-01'
        end <- '2018-01-01'
      } else if(period == 'Yellen->Powell') {
        start <- '2014-01-01'
        end <- '2022-01-01'
      } else {
        start <- '2006-01-01'
        end <- '2022-01-01'
      }
      tmpDat <- toAnalDyadKids %>%
        filter(date > as.Date(start) & date < as.Date(end),
               chamber == chamb
        ) %>%
        filter(grepl('FED',respondingTo),
               !grepl('FED',opensecretsID)) %>%
        group_by(opensecretsID) %>%
        mutate(n = n(),
               yellen = ifelse(grepl('YELLEN',respondingTo),1,0),
               keep = any(grepl('FED',respondingTo))) %>%
        ungroup() %>%
        filter(n > 1,
               keep)
      
      summary(modList[[paste0(chamb,'_',mod)]][[period]] <- felm(as.formula(paste0('interruptorPct ~ yellen*',mod,
                                                                                   ' + nKids + scale(age) + scale(nominate_dim1) + gender + party + scale(seniority) + scale(anyBill)',
                                                                                   ' + combToxic + combIncoh + combAttack + log(tot_utterances+1)',
                                                                                   '| 0 | 0 | 0')),tmpDat))
      # modList[[paste0(chamb,'_',mod)]]$nPoints <- length(unique(tmpDat[[mod]]))
    }
  }
}

summary(modList$House_anyDaughters$`Bernanke->Yellen`)
toplot <- NULL
for(m in names(modList)) {
  for(p in names(modList[[m]])) {
    inc <- ifelse(grepl('propDaughters',m),.2,1)
    toplot <- bind_rows(toplot,as_tibble(data.frame(interaction_plot_continuous(model = modList[[m]][[p]],incr = inc)[[1]])) %>%
                          mutate(model = m,
                                 period = p))
  }
}

toplot <- toplot %>%
  mutate(chamber = gsub('_.*','',model),
         moderator = gsub('.*_','',model),
         # party = ifelse(grepl('_DEM',model),'DEM','GOP'),
         sig = ifelse(pval <= .05,'Sig','Insig'),
         est = gsub('Interaction: ','Interaction:\n',gsub(' \\(','\n\\(',est)),
         period = factor(period,levels = c('Full','Bernanke->Yellen','Yellen->Powell')))

pdf('../Paper/Figures/firstDaughter_mfx.pdf',width = 8,height = 4)
toplot %>%
  filter(moderator == 'firstDaughter') %>%
  ggplot(aes(x = x_2,y = delta_1,label = est)) + 
  geom_hline(yintercept = 0,linetype = 'dashed') + 
  geom_point() + 
  geom_errorbar(aes(ymin = lb,ymax = ub),width = 0) + 
  facet_grid(chamber~period,scales ='free') + 
  scale_x_continuous(breaks = c(0,1),labels = c('No','Yes'),expand = c(.5,0)) + 
  theme_ridges() + 
  xlab('First child is daughter') + ylab('Marginal Effect of Yellen') + 
  geom_text(data = toplot %>%
              filter(moderator == 'firstDaughter') %>%
              select(est,sig,chamber,period) %>%
              distinct() %>%
              mutate(x_2 = .5,delta_1 = -Inf),hjust = .5,vjust = 0,color = 'black') + 
  theme(legend.position = 'bottom',
        strip.background = element_rect(fill = 'white',color = 'black',size = .5,linetype = 'solid'))
dev.off()

pdf('../Paper/Figures/anyDaughters_mfx.pdf',width = 8,height = 4)
toplot %>%
  filter(moderator == 'anyDaughters') %>%
  ggplot(aes(x = x_2,y = delta_1,label = est)) + 
  geom_hline(yintercept = 0,linetype = 'dashed') + 
  geom_point() + 
  geom_errorbar(aes(ymin = lb,ymax = ub),width = 0) + 
  facet_grid(chamber~period,scales ='free') + 
  scale_x_continuous(breaks = c(0,1),labels = c('No','Yes'),expand = c(.5,0)) + 
  theme_ridges() + 
  xlab('Any Daughters') + ylab('Marginal Effect of Yellen') + 
  geom_text(data = toplot %>%
              filter(moderator == 'anyDaughters') %>%
              select(est,sig,chamber,period) %>%
              distinct() %>%
              mutate(x_2 = .5,delta_1 = Inf),hjust = .5,vjust = 1,color = 'black') + 
  theme(legend.position = 'bottom',
        strip.background = element_rect(fill = 'white',color = 'black',size = .5,linetype = 'solid'))
dev.off()

pdf('../Paper/Figures/nDaughters_mfx.pdf',width = 8,height = 4)
toplot %>%
  filter(moderator == 'nDaughters') %>%
  ggplot(aes(x = x_2,y = delta_1,label = est)) + 
  geom_hline(yintercept = 0,linetype = 'dashed') + 
  geom_point() + 
  geom_errorbar(aes(ymin = lb,ymax = ub),width = 0) + 
  facet_grid(chamber~period,scales ='free') + 
  # scale_x_continuous(breaks = c(0,1),labels = c('No','Yes'),expand = c(.5,0)) + 
  theme_ridges() + 
  xlab('Number of Daughters') + ylab('Marginal Effect of Yellen') + 
  # scale_color_manual(name = 'Interaction',values = c('grey70','black'),labels = c('Insignificant','Significant')) + 
  geom_text(data = toplot %>%
              filter(moderator == 'nDaughters') %>%
              select(est,sig,chamber,period) %>%
              distinct() %>%
              mutate(x_2 = 2.5,delta_1 = -Inf),hjust = .5,vjust = 0,color = 'black') + 
  theme(legend.position = 'bottom',
        strip.background = element_rect(fill = 'white',color = 'black',size = .5,linetype = 'solid'))
dev.off()



pdf('../Paper/Figures/propDaughters_mfx.pdf',width = 8,height = 4)
toplot %>%
  filter(moderator == 'propDaughters') %>%
  ggplot(aes(x = x_2,y = delta_1,label = est)) + 
  geom_hline(yintercept = 0,linetype = 'dashed') + 
  geom_point() + 
  geom_errorbar(aes(ymin = lb,ymax = ub),width = 0) + 
  facet_grid(chamber~period,scales ='free') + 
  # scale_x_continuous(breaks = c(0,1),labels = c('No','Yes'),expand = c(.5,0)) + 
  theme_ridges() + 
  xlab('Proportion of Daughters') + ylab('Marginal Effect of Yellen') + 
  # scale_color_manual(name = 'Interaction',values = c('grey70','black'),labels = c('Insignificant','Significant')) + 
  geom_text(data = toplot %>%
              filter(moderator == 'propDaughters') %>%
              select(est,sig,chamber,period) %>%
              distinct() %>%
              mutate(x_2 = .5,delta_1 = -Inf),hjust = .5,vjust = 0,color = 'black') + 
  theme(legend.position = 'bottom',
        strip.background = element_rect(fill = 'white',color = 'black',size = .5,linetype = 'solid'))
dev.off()



# Goddamned APSR
mList <- list()
for(i in paste0(c('House_','Senate_'),'anyDaughters')) {
  for(j in names(modList[[i]])) {
    mList[[paste0(i,': ',j)]] <- modList[[i]][[j]]
  }
}

stargazer(mList,
          # keep = 'yellen|year|interrupted|SENT|nchars',
          column.labels = gsub('_anyDaughters','',names(mList)),
          star.char = c('\\dag','*','**','***'),star.cutoffs = c(.1,.05,.01,.001),
          keep.stat = c('n','rsq'),out = '../Paper/Tables/fig_9_table.tex')


# Same shit but at utterance level
dims <- colnames(utterance_level %>% select(matches('SENT_'),-matches('_lag|error|comb')))

toAnalDyadKids <- utterance_level %>% 
  mutate(anyDaughters = ifelse(nDaughters == 0,0,1),
         propDaughters = nDaughters / nKids,
         noKids = ifelse(nKids == 0,1,0)) %>%
  mutate(propDaughters = ifelse(is.na(propDaughters),0,propDaughters)) %>%
  mutate(respondingTo = relevel(factor(respondingTo),ref = 'FEDBERNANKE'))

modList <- list()
for(mod in c('nDaughters','firstDaughter','anyDaughters','propDaughters')) {
  for(chamb in c('House','Senate')) {
    for(period in c('Bernanke->Yellen','Yellen->Powell','Full')) {
      if(period == 'Bernanke->Yellen') {
        start <- '2006-01-01'
        end <- '2018-01-01'
      } else if(period == 'Yellen->Powell') {
        start <- '2014-01-01'
        end <- '2022-01-01'
      } else {
        start <- '2006-01-01'
        end <- '2022-01-01'
      }
      tmpDat <- toAnalDyadKids %>%
        filter(date > as.Date(start) & date < as.Date(end),
               chamber == chamb
        ) %>%
        filter(grepl('FED',respondingTo),
               !grepl('FED|EXPERT',opensecretsID)) %>%
        group_by(opensecretsID) %>%
        mutate(n = n(),
               yellen = ifelse(grepl('YELLEN',respondingTo),1,0)) %>%
        ungroup() %>%
        filter(all > 30,ind > mind)
      
      summary(modList[[paste0(chamb,'_',mod)]][[period]] <- felm(as.formula(paste0('interruptor ~ yellen*',mod,' + ',
                                                                                   paste(paste0('topic_',1:100,'_lag'),collapse = ' + '),
                                                                                   ' + ',
                                                                                   paste(paste0('scale(',dims,'_lag)'),collapse = ' + '),
                                                                                   ' + poly(scale(log(nchars_lag+1)),3) + poly(scale(log(tot_utterances)),3) + interrupted',
                                                                                   '| opensecretsID | 0 | opensecretsID')),tmpDat))
      # modList[[paste0(chamb,'_',mod)]]$nPoints <- length(unique(tmpDat[[mod]]))
    }
  }
}

summary(modList$House_anyDaughters$`Bernanke->Yellen`)
toplot <- NULL
for(m in names(modList)) {
  for(p in names(modList[[m]])) {
    inc <- ifelse(grepl('propDaughters',m),.2,1)
    toplot <- bind_rows(toplot,as_tibble(data.frame(interaction_plot_continuous(model = modList[[m]][[p]],incr = inc)[[1]])) %>%
                          mutate(model = m,
                                 period = p))
  }
}

toplot <- toplot %>%
  mutate(chamber = gsub('_.*','',model),
         moderator = gsub('.*_','',model),
         # party = ifelse(grepl('_DEM',model),'DEM','GOP'),
         sig = ifelse(pval <= .05,'Sig','Insig'),
         est = gsub('Interaction: ','Interaction:\n',gsub(' \\(','\n\\(',est)),
         period = factor(period,levels = c('Full','Bernanke->Yellen','Yellen->Powell')))

toplot %>%
  filter(moderator == 'propDaughters') %>%
  ggplot(aes(x = x_2,y = delta_1,label = est)) + 
  geom_hline(yintercept = 0,linetype = 'dashed') + 
  geom_point() + 
  geom_errorbar(aes(ymin = lb,ymax = ub),width = 0) + 
  facet_grid(chamber~period,scales ='free') + 
  scale_x_continuous(breaks = c(0,1),labels = c('No','Yes'),expand = c(.5,0)) + 
  theme_ridges() + 
  xlab('Any Daughters') + ylab('Marginal Effect of Yellen') + 
  geom_text(data = toplot %>%
              filter(moderator == 'propDaughters') %>%
              select(est,sig,chamber,period) %>%
              distinct() %>%
              mutate(x_2 = .5,delta_1 = -Inf),hjust = .5,vjust = 0,color = 'black') + 
  theme(legend.position = 'bottom',
        strip.background = element_rect(fill = 'white',color = 'black',size = .5,linetype = 'solid'))



# Interest group ratings?
# toAnalDyadIG <- toAnalDyad %>% 
#   mutate(year = lubridate::year(date)) %>%
#   left_join(IG %>% filter(!IG %in% c('Concerned Women for America','American Congress of Obstetricians and Gynecologists')) %>% 
#               group_by(opensecretsID,year) %>% summarise(rating = mean(rating,na.rm=T))) %>%
#   mutate(respondingTo = relevel(respondingTo,ref = 'ChairpersonBernanke'))
# modList <- list()
# for(chamb in c('House','Senate')) {
#   # stop()
#   tmpDat <- toAnalDyadIG %>%
#     filter(date > as.Date('2006-01-01') & date < as.Date('2018-01-01'),
#            chamber == chamb) %>%
#     filter(grepl('Yellen|Bernanke|Powell|Greenspan',respondingTo),
#            !grepl('Yellen|Bernanke|Powell|Greenspan|Expert',speaker)) %>%
#     group_by(id) %>%
#     mutate(n = n(),
#            keep = any(grepl('Yellen',respondingTo)) & any(grepl('Bernanke',respondingTo))) %>%
#     ungroup() %>%
#     filter(n > 1,
#            keep)
#   if(nrow(tmpDat) == 0) { next }
#   # stop()
#   summary(modList[[paste0(chamb)]] <- felm(as.formula(paste0('interruptorPct ~ factor(respondingTo)*rating',
#                                                              '| opensecretsID | 0 | opensecretsID')),tmpDat))
#   
# }
# 
# toplot <- NULL
# for(m in names(modList)) {
#   toplot <- bind_rows(toplot,as_tibble(data.frame(interaction_plot_continuous(model = modList[[m]],num_points = 10)[[1]])) %>%
#                         mutate(model = m))
# }
# 
# toplot <- toplot %>%
#   mutate(est = gsub('Interaction: ','Interaction:\n',gsub(' \\(','\n\\(',est)))
# 
# 
# pdf('../Paper/Figures/IGratings_mfx.pdf',width = 8,height = 4)
# toplot %>%
#   ggplot(aes(x = x_2,y = delta_1,label = est)) + 
#   geom_hline(yintercept = 0,linetype = 'dashed') + 
#   geom_point() + 
#   geom_errorbar(aes(ymin = lb,ymax = ub),width = 0) + 
#   facet_grid(.~model,scales ='free') + 
#   # scale_x_continuous(breaks = c(0,1),labels = c('No','Yes'),expand = c(.5,0)) + 
#   theme_ridges() + 
#   xlab("Women's IG Rating") + ylab('Marginal Effect of Yellen') + 
#   # scale_color_manual(name = 'Interaction',values = c('grey70','black'),labels = c('Insignificant','Significant')) + 
#   geom_text(data = toplot %>%
#               select(est,model) %>%
#               distinct() %>%
#               mutate(x_2 = 50,delta_1 = -Inf),hjust = .5,vjust = 0,color = 'black') + 
#   theme(legend.position = 'bottom',
#         strip.background = element_rect(fill = 'white',color = 'black',size = .5,linetype = 'solid'))
# dev.off()